﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ACompany.OrderProcessing.Model;
using ACompany.OrderProcessing.Services;

namespace ACompany.OrderProcessing.Presentation.Product
{
    public class ProductListPresenter
    {
        private readonly IProductListView _view;
        private readonly IProductService _productService;
        private readonly IOrderService _orderService;

        #region ctors
        public ProductListPresenter(IProductListView view)
            : this(view, new ProductService(), new OrderService())
        {
        }

        public ProductListPresenter(IProductListView view, IProductService ProductService, IOrderService orderService)
        {
            _productService = ProductService;
            _orderService = orderService;
            _view = view;
        }
        #endregion

        #region methods
        public void Display()
        {
            ClearInfoAndErrorMessages();
            _view.Products = _productService.FindAll().ToList();
            _view.ViewTitle("Product List");
        }

        public void RemoveProductBy(Guid productId)
        {
            ClearInfoAndErrorMessages();

            if (_orderService.FindAllOrdersContainingProductby(productId).Count == 0)
            {
                Model.Product product = _productService.FindBy(productId);
                if (product != null)
                {
                    _productService.Remove(product);
                    Display();
                }
                else
                {
                    _view.ErrorMessage(string.Format("there is no product with id:{0}", productId));
                }
            }
            else
            {
                _view.ErrorMessage("cannot delete a product that has orders");
            }
        }

        private void ClearInfoAndErrorMessages()
        {
            _view.InfoMessage(string.Empty);
            _view.ErrorMessage(string.Empty);
        }
        #endregion
    }
}
